package com.guiji.quartz.domain;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.wanghaomiao.xpath.exception.NoSuchAxisException;
import cn.wanghaomiao.xpath.exception.NoSuchFunctionException;
import cn.wanghaomiao.xpath.exception.XpathSyntaxErrorException;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.common.utils.spring.SpringUtils;
import com.guiji.quartz.formatter.DataTemplateFormatter;
import com.guiji.quartz.service.ISpiderNewsService;
import com.guiji.quartz.service.RedisService;
import com.guiji.quartz.task.DataSaveUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @create: 2021-09-06 17:28
 **/
public class XinhuaEnglishWorld {
	private static final Logger log = LoggerFactory.getLogger(ChinaDaily2.class);

	public static void mainMethod() throws NoSuchFunctionException, XpathSyntaxErrorException, NoSuchAxisException {
		List<String> entry = getEntry();
		String resp = null;
		try {
			HttpResponse response = HttpRequest.get(entry.get(0)).
				header("accept-encoding", "gzip, deflate, br")
				.header("Cookie", "HMF_CI=0f6ce03ea60c5d8ff902a5ac8be105650af28965ad25f7aabf17d4424e0dac85d9")
				.setConnectionTimeout(15000)
				.execute();
			resp = response.body();
		} catch (HttpException e) {
			return;
		}
		//获取子链接
		List<String> listContent = getContentUrl(resp);
		//爬取具体内容
		getContent(listContent);

	}

	private static void getContent(List<String> listContent) throws NoSuchFunctionException, XpathSyntaxErrorException, NoSuchAxisException {
		for (String url : listContent) {
			String doc = null;
			try {
				HttpResponse response = HttpRequest.get(url)
					.header("accept-encoding", "gzip, deflate, br")
					.header("Cookie", "HMF_CI=0f6ce03ea60c5d8ff902a5ac8be105650af28965ad25f7aabf17d4424e0dac85d9")
					.setConnectionTimeout(15000)
					.execute();
				doc = response.body();
			} catch (HttpException e) {
				continue;
			}
			JXDocument jxDocument = new JXDocument(doc);
			String title = null;
			try {
				title = (String) jxDocument.sel("//h1/text()").get(0);
			} catch (Exception e) {
				System.out.println("标题错误-------------" + url + "-------------------标题错误");
			}
			StringBuffer content = new StringBuffer();
			jxDocument.sel("//div[@class='content']//p/text()").forEach(s -> {
				content.append(s + "$$$");
			});

			List<Object> imgs = null;
			imgs = jxDocument.sel("//div[@class='content']//p//img/@src");
			List<String> newImgs = dealPic(imgs);

			Document document = Jsoup.parse(doc);
			DataTemplateFormatter dataTemplateFormatter = new DataTemplateFormatter();

			Date date = null;
			try {
				date = dataTemplateFormatter.format(document.getElementsByClass("time").toString().replaceAll("<.*?>", "").trim());
			} catch (Exception e) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String s = sdf.format(new Date());
				date = dataTemplateFormatter.format(s + " 00:00  ");
			}


			if (content.length() > 5000 || content.toString().replaceAll("\\$|[\\s\\p{Zs}]","").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				int i = RandomUtil.randomInt(1, 4);
				DataSaveUtil.saveData(title, content.toString(), newImgs, url, date, "http://www.xinhuanet.com/english/sports/index.htm", "Xinhua-EnglishWorld-"+i);
				log.info(Thread.currentThread().getName() + "-----------------XinhuaWorld----------------");
			} catch (Exception e) {
				continue;
			}
		}
	}

	private static List<String> dealPic(List<Object> imgList) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String[] ss = sdf.format(new Date()).split("-");
		String year = ss[0];
		String mon = ss[1];
		String day = ss[2];
		List<String> newImg = new ArrayList<>();
		for (Object s : imgList) {
			String img = "http://www.news.cn/english/" + year + "-" + mon + "/" + day + "/" + s.toString();
			try {
				String s1 = HttpUtil.get(img);
				newImg.add(img);
			} catch (Exception e) {
				continue;
			}
		}
		return newImg;
	}

	private static List<String> getContentUrl(String content) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String s = sdf.format(new Date());
		String[] ss = sdf.format(new Date()).split("-");
		String year = ss[0];
		String mon = ss[1];

		List<String> res = new ArrayList<>();
		String pattern = "(https://english.news.cn)?(\\.\\.)?/([a-z]{3,20}/)?"+year+mon+"[0-9]{2}/[0-9|a-z]*?/c.html";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		while (m.find()) {
			if(m.group().contains("https")){
				res.add(m.group());
			}else {
				res.add("https://english.news.cn"+m.group().substring(2));
			}

		}
		return res;
	}


	public static List<String> getEntry() {
		List<String> listEntry = new ArrayList<>();
		listEntry.add("http://www.news.cn/english/world/index.htm");
		return listEntry;
	}

//	public static void main(String[] args) throws NoSuchFunctionException, XpathSyntaxErrorException, NoSuchAxisException {
//		mainMethod();
//	}
}
